package com.example.myproject;
import java.util.ArrayList;

import javax.jdo.PersistenceManager;


public class HouseRentalLocations {

	ArrayList<House> nearestHouse = new ArrayList<House>();
	double centerLat, centerLng,radius;
	public static int check=0;

	public HouseRentalLocations(double centerLat, double centerLng,double radius){
		this.centerLat = centerLat;
		this.centerLng = centerLng;
		this.radius = radius ;
	}
	
	public ArrayList<House> getArrayList(){
		//write code to populate nearestHouse
		//incorporate mem-cache
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		String query = "select from " + House.class.getName();
		java.util.List<House> house = (java.util.List<House>)(pm.newQuery(query).execute());
		 if (house!=null) {
			 java.util.Iterator<House> houseIterator = house.iterator();
			 	while(houseIterator.hasNext()){
			 		House houseRef = houseIterator.next();
			 		if(computeDistanceDecision(centerLat,centerLng,houseRef.getLat(), houseRef.getLng())){
			 			
			 			nearestHouse.add(houseRef);
			 			check++;
			 		}
			 		
		 }				

	}
		 
		return nearestHouse;
	}
	
	private boolean computeDistanceDecision(double lat1,double lng1,double lat2,double lng2){
		int R = 6371;
		double dLat= ((lat1-lat2) * Math.PI)/180;
		double dLng= ((lng1-lng2) * Math.PI)/180;
		
		double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos((lat1 * Math.PI) / 180) * Math.cos((lat2 * Math.PI)/180) * 
        Math.sin(dLng/2) * Math.sin(dLng/2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
		double d = R * c;
		if(d <= radius){
			return true;
		}
		else{
			return false;
		}
		
	}
}
